<template>
  <y-dialog width="400px" append-to-body>
    <el-upload multiple :action="uploadFileUrl" :file-list="fileList" :limit="limit" :accept="fileType"
      :before-upload="handleBeforeUpload" :on-error="handleUploadError" :on-exceed="handleExceed"
      :on-success="handleUploadSuccess" :show-file-list="true" :headers="headers" ref="uploadRef" drag>
      <el-icon class="el-icon--upload">
        <upload-filled />
      </el-icon>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <template #tip>
        <div class="el-upload__tip text-center">
          <span>大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>仅允许导入<b style="color: #f56c6c">{{
            fileType
          }}</b>格式文件。</span>
        </div>
      </template>
    </el-upload>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submit">确 定</el-button>
        <el-button @click="emit('close')">取 消</el-button>
      </div>
    </template>
  </y-dialog>
</template>

<script setup name="YFileUpload">
import { getToken, tokenKey } from "@/utils/auth";

const { proxy } = getCurrentInstance();

const emit = defineEmits(['submited', 'close'])

// 设置上传的请求头部
const headers = { Authorization: "Bearer " + getToken(tokenKey.access) };

const props = defineProps({
  url: {
    type: String,
    default: "/sys/file/",
  },
  files: [String, Object, Array],
  // 数量限制
  limit: {
    type: Number,
    default: 5,
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 50,
  },
  // 文件类型, 例如".json,.doc,.docx,.xls,.xlsx,.csv,.ppt,.xml,.txt,.pdf"
  fileType: {
    type: String,
    default: ".json,.doc,.docx,.xls,.xlsx,.csv,.ppt,.xml,.txt,.pdf",
  },
});

const uploadList = ref([]);
const fileList = ref([]);

// 上传文件服务器地址
const uploadFileUrl = computed(() => {
  return import.meta.env.VITE_APP_BASE_API + props.url
});

// 上传前校检格式和大小
function handleBeforeUpload(file) {
  // 校检文件类型
  if (props.fileType.length) {
    const fileName = file.name.split('.');
    const fileExt = fileName[fileName.length - 1];
    const isTypeOk = props.fileType.indexOf(fileExt) >= 0;
    if (!isTypeOk) {
      proxy.$modal.msgError(`文件格式不正确, 请上传${props.fileType}格式文件!`);
      return false;
    }
  }
  // 校检文件大小
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize;
    if (!isLt) {
      proxy.$modal.msgError(`上传文件大小不能超过 ${props.fileSize} MB!`);
      return false;
    }
  }
  proxy.$modal.loading("正在上传文件，请稍候...");
  // number.value++;
  return true;
}

// 文件个数超出
function handleExceed() {
  proxy.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
}

// 上传失败
function handleUploadError(err) {
  proxy.$modal.msgError("上传文件失败");
}

// 上传成功回调
function handleUploadSuccess(res, file) {
  if (res.code === 200) {
    uploadList.value.push(res.data);
    proxy.$modal.closeLoading();
  } else {
    proxy.$modal.closeLoading();
    proxy.$modal.msgError(res.msg);
  }
}

/** 提交上传文件 */
function submit() {
  emit('submited')
  emit('close')
};


/** Expose方法 */
defineExpose({
  uploadList,
});
</script>
